package org.opens.p6spy;

import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.FormattedLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;


/**
 * <p>
 * P6spy日志实现
 * </p>
 *
 * @author tzq
 * @date 2019-08-08 9:54
 */
@Slf4j
public class P6spyLogger extends FormattedLogger {

    // 设置请求参数截取长度阈值, 高于这个值将进行截取, 设置为-1则不截取.
    private static final int REQUEST_PARAM_MESSAGE_LENGTH = 300;

    @Override
    public void logException(Exception e) {
        log.info("", e);
    }

    @Override
    public void logText(String text) {
        log.info(text);
    }

    @Override
    public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql, String url) {
        final String msg = strategy.formatMessage(connectionId, now, elapsed,
                category.toString(), prepared, sql, url);
        if (StringUtils.isEmpty(msg)) {
            return;
        }

        if (Category.ERROR.equals(category)) {
            log.error(msg + "; time: " + elapsed);
        } else if (Category.WARN.equals(category)) {
            log.warn(msg + "; time: " + elapsed);
        } else if (Category.DEBUG.equals(category)) {
            log.debug(msg + "; time: " + elapsed);
        } else {
            log.info(msg + "; time: " + elapsed);
        }
    }

    @Override
    public boolean isCategoryEnabled(Category category) {
        if (Category.ERROR.equals(category)) {
            return log.isErrorEnabled();
        } else if (Category.WARN.equals(category)) {
            return log.isWarnEnabled();
        } else if (Category.DEBUG.equals(category)) {
            return log.isDebugEnabled();
        } else {
            return log.isInfoEnabled();
        }
    }
}
